<template>
  <div class="container">
    <div class="app-container">
      <!-- 按钮 -->
      <el-button type="primary" size="mini" @click="addRoles">添加角色</el-button>
      <!-- 表格 el-table -->
      <el-table :data="roleList">
        <el-table-column prop="name" align="center" width="200" label="角色">
          <template #default="{row}">
            <!-- row 行的数据 -->
            <!-- row.isEdit true 编辑状态 / false -->
            <el-input v-if="row.isEdit" v-model.trim="row.rowEdit.name" size="mini" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <template #default="{row}">
            <!-- 已启用  未启用 无 -->
            <!-- state 1 0 -1 -->
            <el-switch
              v-if="row.isEdit"
              v-model="row.rowEdit.state"
              :active-value="1"
              :inactive-value="0"
            />
            <span v-else>{{ row.state===1?'已启用':row.state===0?'未启用':'无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template #default="{row}">
            <el-input v-if="row.isEdit" v-model.trim="row.rowEdit.description" type="textarea" size="mini" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="{row}">
            <!-- 空标签, 当前template被解析之后, 不会显示任何的节点 -->
            <!-- <template></template> -->
            <template v-if="row.isEdit">
              <el-button size="mini" type="primary" @click="confirmEdit(row)">确认</el-button>
              <el-button size="mini" @click="row.isEdit=false">取消</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="mini" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button type="text" style="margin-right:10px" size="mini" @click="edit(row)">编辑</el-button>
              <el-popconfirm
                title="您确认要删除该角色吗?"
                @onConfirm="delRole(row)"
              >
                <template #reference>
                  <el-button type="text" size="mini">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 布局组件 -->
      <el-row type="flex" justify="end" align="middle" style="height:60px">
        <!-- 分页  el-pagination -->
        <el-pagination
          layout="prev, pager, next"
          :current-page="pageParams.page"
          :page-size="5"
          :total="total"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>
    <!-- 新增角色弹出框 -->
    <el-dialog
      title="新增角色"
      :visible.sync="showDialog"
      width="500px"
      @close="close"
    >
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item label="角色名称" prop="name" label-width="120px">
          <el-input v-model="form.name" size="mini" />
        </el-form-item>
        <el-form-item label="启用" prop="state" label-width="120px">
          <el-switch
            v-model="form.state"
            active-color="#13ce66"
            inactive-color="#dcdfe6"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description" label-width="120px">
          <el-input v-model="form.description" size="mini" type="textarea" :rows="3" style="width:300px" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="end">
            <el-col :span="13">
              <el-button type="primary" size="mini" @click="confirm">确定</el-button>
              <el-button size="mini" @click="close">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 分配权限弹出框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="showPermissionDialog"
    >
      <!-- 树形组件 -->
      <el-tree
        ref="tree"
        :data="permissionData"
        :props="{label:'name'}"
        node-key="id"
        :default-checked-keys="permIds"
        default-expand-all
        show-checkbox
      />
      <template #footer>
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <el-button size="mini" type="primary" @click="btnPermissionConfirm">确认</el-button>
            <el-button size="mini" @click="showPermissionDialog=false">取消</el-button>
          </el-col>
        </el-row>
      </template>
    </el-dialog>
  </div>
</template>
<script>
import { addRole, assignPrem, getRoleDetail, getRoleList, roleDel, roleEdit } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { translateListToTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      currentRoleId: null, // 被选中项的id
      showPermissionDialog: false, // 控制分配权限弹出层的展示
      permissionData: [], // 接收权限树数据
      permIds: [], // 当前角色的权限列表
      // 新增角色表单数据
      form: {
        name: '',
        description: '',
        state: 0
      },
      // 表单验证规则
      rules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      },
      showDialog: false,
      total: 0,
      pageParams: {
        page: 1,
        pagesize: 5
      },
      roleList: []
    }
  },
  created() {
    this.getRoleList(this.pageParams)
  },
  methods: {
    // 点击弹出分配权限弹出层
    async   btnPermission(id) {
      this.permIds = []
      this.currentRoleId = id
      // 1. 获取权限列表数据
      const list = await getPermissionList()
      this.permissionData = translateListToTreeData(list, 0)
      // 2. 根据角色id获取角色详情 - 包含了角色对应的权限
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      // 3. 显示弹出层
      this.showPermissionDialog = true
    },
    // 点击弹出分配权限弹出层的确认按钮
    async  btnPermissionConfirm() {
      const permIds = this.$refs.tree.getCheckedKeys()
      await assignPrem({ id: this.currentRoleId, permIds })
      this.$message.success('分配权限成功')
      this.showPermissionDialog = false
    },
    // 删除角色
    async delRole(row) {
      await roleDel(row.id)
      this.$message.success('删除角色成功')
      // 如果删除的是最后一个,会进行处理
      if (this.roleList.length === 1 && this.pageParams.page > 1) this.pageParams.page--
      this.getRoleList(this.pageParams)
    },
    // 确认编辑事件
    async  confirmEdit(row) {
      // 1. 判断表单的值是否为空
      if (row.rowEdit.name && row.rowEdit.description) {
        // 2. 发送请求 - 更新数据
        await roleEdit({ ...row.rowEdit, id: row.id })
        // 3. 更新显示数据
        // eslint-disable-next-line require-atomic-updates
        // row.name = row.rowEdit.name // eslint校验工具 误判
        // Object.assign(目标对象,源对象1,源对象2,....)
        Object.assign(row, { ...row.rowEdit, isEdit: false })
        // 4. 退出编辑状态 isEdit ---> false
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    // 行编辑
    edit(row) {
      row.isEdit = true // 进入到了编辑状态
      // 更新缓存数据
      row.rowEdit = { name: row.name, state: row.state, description: row.description }
    },
    // 确认按钮
    async  confirm() {
      await this.$refs.form.validate()
      await addRole(this.form)
      this.$message.success('新增角色成功')
      this.close()
      this.getRoleList(this.pageParams)
    },
    // 取消
    close() {
      this.$refs.form.resetFields()
      this.showDialog = false
    },
    // 添加角色事件
    addRoles() {
      this.showDialog = true
    },
    // 切换分页事件
    handleCurrentChange(value) {
      this.pageParams.page = value
      this.getRoleList(this.pageParams)
    },
    // 获取角色列表
    async getRoleList(data) {
      const { rows, total } = await getRoleList(data)
      this.total = total
      this.roleList = rows
      this.roleList.forEach(item => {
        // Object.defineProperty
        // vue中动态添加的属性 不具备响应式的能力
        // 响应式：数据变化 - 视图自动更新
        // 如何动态的往对象中添加属性，而且还具备响应式能力???
        // this.$set(目标对象,属性,属性值)
        // item.isEdit = false  // isEdit 是否进入编辑状态 默认是false
        this.$set(item, 'isEdit', false)
        // 增加一个缓存数据
        this.$set(item, 'rowEdit', { name: item.name, state: item.state, description: item.description })
      })
    }
  }
}
</script>
<style scoped>
.role-operate {
  padding: 10px;
}
</style>
